import { BasicDrawer, useDrawer, useDrawerInner } from "@/components/Drawer";
import { useState, useMemo } from "react";
import { BasicForm, useForm, FormSchema } from "@/components/Form";
import { FinancePaymentApi } from "@/api/erp/finance/payment";
import { message, Tabs } from "antd";
import { useTranslation } from "react-i18next";
import { BasicProTable, useProTable } from "@/components/ViewComponents/proTable";
import { Button } from "antd";
import { AccountApi } from "@/api/erp/finance/account";
import * as UserApi from "@/api/system/user";
import { SupplierApi } from "@/api/erp/purchase/supplier";
import StockInFormDetailIn from "@/views/erp/drugStorage/purchase/in/PurchaseInPaymentEnableList";
import StockInFormDetailReturn from "@/views/erp/drugStorage/purchase/return/PurchaseReturnRefundEnableList";
const newAdd = (props: { register: Fn }) => {
	const en_vi = "drugStorage.inventoryManagement";
	const en_vi1 = "drugStorage.financialManagement.paymentOrder";
	const { t } = useTranslation();
	const [id, setId] = useState(0);
	let reload: Function;
	const [isUpdated, setIsUpdated] = useState(false);
	const ErpBizType = {
		PURCHASE_ORDER: 10,
		PURCHASE_IN: 11,
		PURCHASE_RETURN: 12,
		SALE_ORDER: 20,
		SALE_OUT: 21,
		SALE_RETURN: 22
	};
	const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(props.register, data => {
		reload = data.reload;
		resetFields();
		setDrawerProps({ confirmLoading: true });
		setIsUpdated(!!data?.isUpdated);
		setId(data.record?.id);
		data.isUpdated
			? setFieldsValue(data.record?.items)
			: setFieldsValue([
					{
						key: new Date().getTime(),
						bizId: undefined,
						bizType: undefined,
						bizNo: undefined,
						remark: undefined,
						totalPrice: undefined,
						paidPrice: undefined,
						paymentPrice: undefined
					}
			  ]);
		setFieldsValueFn({
			...data.record
		});
		setDrawerProps({ confirmLoading: false });
	});
	const getTitle = useMemo(() => {
		return isUpdated ? t(`${en_vi}.warehouseInformation.editWarehouseInfo`) : t(`${en_vi}.warehouseInformation.addWarehouseInfo`);
	}, [isUpdated]);
	const formItems: FormSchema[] = [
		{
			label: t(`drugStorage.financialManagement.paymentOrder.paymentOrderNumber`),
			field: "pmtId",
			component: "Input",
			componentProps: {
				disabled: true,
				placeholder: t("drugStorage.automaticallySaving")
			}
		},
		{
			component: "DatePicker",
			label: t(`drugStorage.financialManagement.paymentOrder.paymentTime`),
			field: "paymentTime"
		},
		{
			label: t(`drugStorage.purchasingManagement.purchaseOrder.suplerId`),
			component: "ApiSelect",
			field: "suplerId",
			componentProps: {
				api: SupplierApi.getSupplierSimpleList,
				labelField: "name",
				valueField: "suplerId",
				immediate: false
			}
		},
		{
			label: t(`drugStorage.purchasingManagement.purchaseOrder.account`),
			component: "ApiSelect",
			field: "accountId",
			componentProps: {
				api: AccountApi.getAccountSimpleList,
				labelField: "name",
				valueField: "id",
				immediate: false
			}
		},
		{
			label: t(`${en_vi}.inventoryDetails.createdBy`),
			component: "ApiSelect",
			field: "createdBy",
			componentProps: {
				api: UserApi.getListSimpleUsers,
				labelField: "nickname",
				valueField: "id",
				immediate: false
			}
		},
		{
			label: t(`drugStorage.salesManagement.saleOrder.discountPrice`),
			component: "InputNumber",
			field: "discountPrice"
		},
		{
			label: t(`${en_vi1}.totalPrice`),
			component: "InputNumber",
			field: "totalPrice"
		},
		{
			label: t(`${en_vi1}.paymentPrice`),
			component: "InputNumber",
			field: "paymentPrice"
		},
		{
			label: t(`${en_vi}.warehouseInformation.remark`),
			component: "InputTextArea",
			field: "remark",
			colProps: { span: 24 }
		}
	];
	const [formTop, { validateFields, setFieldsValue: setFieldsValueFn, resetFields }] = useForm({
		schemas: formItems,
		labelWidth: 150,
		baseColProps: { span: 12 }
	});
	const dataSource = [
		{
			key: new Date().getTime(),
			bizId: undefined,
			bizType: undefined,
			bizNo: undefined,
			remark: undefined,
			totalPrice: undefined,
			paidPrice: undefined,
			paymentPrice: undefined
		}
	];
	const defaultColumns = [
		{
			title: t("felix_ui.sq_numb"),
			// dataIndex: "sq_numb",
			render: (text, record, index) => index * 1 + 1 // 设置序号
		},
		{
			title: t(`${en_vi1}.bizNo`),
			dataIndex: "bizNo"
		},
		{
			title: t("felix_ui.remark"),
			dataIndex: "remark",
			editable: true
		},
		{
			title: t(`${en_vi1}.totalPrice`),
			dataIndex: "totalPrice",
			fixed: "right"
		},
		{
			title: t(`${en_vi1}.paidPrice`),
			dataIndex: "paidPrice",
			fixed: "right"
		},
		{
			title: t(`${en_vi1}.paymentPrice`),
			dataIndex: "paymentPrice",
			editable: true,
			fixed: "right"
		},

		{
			title: t("felix_ui.action"),
			render: (_, obj) => {
				return <Button onClick={onDelete(obj)}>{t("felix_ui.delete")}</Button>;
			},
			fixed: "right"
		}
	];
	const [proTable, { submit, handleAdd, handleDelete, setFieldsValue }] = useProTable({
		defaultColumns,
		dataSource
	});
	const onDelete = obj => () => {
		handleDelete(obj.key);
	};
	const handleSubmit = async () => {
		const values = await validateFields();
		const items = await submit();
		values.paymentTime = new Date(values.paymentTime).getTime();
		values.items = items;
		// values.totalCount = 0;
		// values.totalPrice = 0;
		// items.map((item: any) => {
		// 	values.totalCount += item.count / 1;
		// 	values.totalPrice += item.drugPrice / 1;
		// });
		let res;
		if (isUpdated) {
			values.id = id;
			res = await FinancePaymentApi.updateFinancePayment(values);
		} else {
			res = await FinancePaymentApi.createFinancePayment(values);
		}
		if (!res) {
			message.error(t("viewComponents.patientInformation.additionFailed"));
			return;
		}
		message.success(t("viewComponents.patientInformation.successfullyAdded"));
		closeDrawer();
		reload();
	};
	const [drawerDetailIn, { openDrawer: openDrawerIn }] = useDrawer();
	const [drawerDetailReturn, { openDrawer: openDrawerReturn }] = useDrawer();
	/** 新增【采购入库】按钮操作 */
	const handleOpenPurchaseIn = () => {
		openDrawerIn(true, {
			suplerId: "1"
		});
	};
	const setOrderItemIn = (row: any) => {
		console.log("row", row);
		handleAdd({
			key: row.buyinId,
			bizId: row.buyinId,
			bizType: ErpBizType.PURCHASE_IN,
			bizNo: row.buyinId,
			remark: row.remark,
			totalPrice: row.totalPrice,
			paidPrice: row.paymentPrice,
			paymentPrice: row.totalPrice - row.paymentPrice
		});
	};

	/** 新增【采购退货】按钮操作 */
	const handleOpenPurchaseReturn = () => {
		openDrawerReturn(true, {
			suplerId: "1"
		});
	};
	const setOrderItemReturn = (row: any) => {
		handleAdd({
			key: row.returnId,
			bizId: row.returnId,
			bizType: ErpBizType.PURCHASE_RETURN,
			bizNo: row.returnId,
			remark: row.remark,
			totalPrice: -row.totalPrice,
			paidPrice: -row.refundPrice,
			paymentPrice: -row.totalPrice + row.refundPrice
		});
	};
	return (
		<BasicDrawer size="large" {...props} title={getTitle} register={registerDrawer} ok={handleSubmit} showFooter={true}>
			<Tabs>
				<Tabs.TabPane tab={t("drugStorage.inventorydrugs")}>
					<BasicForm register={formTop}></BasicForm>
					<Button onClick={handleOpenPurchaseIn}> {t(`${en_vi1}.addPurReceipt`)}</Button>
					{/* 可付款的【采购入库单】列表 */}
					<StockInFormDetailIn register={drawerDetailIn} setOrderItem={setOrderItemIn}></StockInFormDetailIn>
					{/* 可付款的【采购入库单】列表 */}
					<StockInFormDetailReturn register={drawerDetailReturn} setOrderItem={setOrderItemReturn}></StockInFormDetailReturn>
					<Button onClick={handleOpenPurchaseReturn}> {t(`${en_vi1}.addPurReturn`)}</Button>
					<div style={{ width: "100%", overflow: "auto" }}>
						<BasicProTable register={proTable}></BasicProTable>
					</div>
				</Tabs.TabPane>
			</Tabs>
		</BasicDrawer>
	);
};
export default newAdd;
